<?php

use Illuminate\Database\Capsule\Manager as DB;

#前台基类
abstract class CommonController extends CoreController
{
    protected $user;

    protected $authExcept = [];

    public function init()
    {
        parent::init();
        $authExcept = array_map('strtolower', $this->authExcept);
        if (in_array($this->action, $authExcept)) {
            // Log::out("{$this->controller}:{$this->action}" . ' no need login');
            $this->user = \app\service\auth::checklogin();
        } else {
            // Log::out("{$this->controller}:{$this->action}" . ' need login');
            $this->user = \app\service\auth::checklogin(true);
        }
    }

    #中间件验证登陆标识
    private function checkToken()
    {
        $middle      = "app\\middleware\\" . strtolower($this->controller);
        if (class_exists($middle)) {
            $this->user = (new $middle)->handle($this->pageParam);
        }
    }

    #验证角色权限
    private function checkRole()
    {
        #检查权限
        $allAuth = remember('role_' . $this->user->user_id, 3600, function () {
            $ownAuth = explode(',', DB::table('members_roles')->find($this->user->roles_id)->menu_ids);
            $rows    = DB::table('members_menus')->whereIn('id', array_values($ownAuth))->select('module', 'controller', 'actions')->get();
            $auth    = [];
            if ($rows->isNotEmpty()) {
                foreach ($rows as $k => $v) {
                    $allact = explode(',', $v->actions);
                    foreach ($allact as $action) {
                        if (!empty($v->module) && !empty($v->controller) && !empty($action)) {
                            array_push($auth, strtolower('/' . $v->module . '/' . $v->controller . '/' . $action));
                        }
                    }
                }
            }
            return $auth;
        });
        if (!in_array(strtolower('/' . $this->module . '/' . $this->controller . '/' . $this->action), $allAuth)) {
            throw new Exception('无访问权限.', 403);
        }
    }

    protected function cleanTableColumn($table, &$rows)
    {
        $columns = [];
        foreach (DB::select("SHOW COLUMNS FROM `{$this->config->database->prefix}{$table}`") as $v) {
            $columns[] = $v->Field;
        }
        foreach ($rows as $k => $v) {
            if (!in_array($k, $columns)) {
                unset($rows[$k]);
            }
        }
    }

}
